package com.uh.microservice.core.util;

import com.uh.microservice.core.CONSTANTS;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by liming on 2017/9/18.
 */
public class Encryption {
    private static String encrypt(String source,String mode) {
        String result = "";
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance(mode);
            byte[]  str=messageDigest.digest(source .getBytes(CONSTANTS.UTF8));
            return Base64.encodeBase64String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String sha1(String content){
       return encrypt(content,CONSTANTS.SECURITY_SHA1);
    }

    public static String encryptPWD(String password){
        return md5(password);
    }

    public static String md5(String content) {
        try{
            MessageDigest messageDigest = MessageDigest.getInstance(CONSTANTS.SECURITY_MD5);
            messageDigest.reset();
            messageDigest.update(content.getBytes(CONSTANTS.UTF8));
            byte[] byteArray = messageDigest.digest();
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                else
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
            String mdstr = md5StrBuff.toString();
            return Base64.encodeBase64String(mdstr.getBytes());
        }catch(Exception e){

        }
        return null;
        // return encrypt(content,CONSTANTS.SECURITY_MD5);
    }

    public static String des_encrypt(String data, String key) {
        try {
            if (StringUtils.isBlank(key)) key = CONSTANTS._DES_PWD;
            byte[] bt = encrypt(data.getBytes(CONSTANTS.UTF8), key.getBytes(CONSTANTS.UTF8));
            String strs = Base64.encodeBase64String(bt);
            return strs;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    public static String des_encrypt(String data){
        return des_encrypt(data,null);
    }

    public static void main(String[] args) {
		System.out.println("APP_ID:" + des_encrypt("2088821611061495"));
		System.out.println("SELLER_MCH_ID:" + des_encrypt("ctkjtest@163.com"));
		System.out.println("PRIVATE_KEY:" + des_encrypt("MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJNbBRKhq+S/Orkk0oaH4hTTIOMycUt3TKL56lNGBz6czZvpuL9znkk9nmgVWHOx/N2+xDU2DSKdXUGyyqEB0M9Dj6nAr9ALP0768+sPsY7Yfxa6foSzRxCBzoyLyrM92Zq07C632xIMO+HTcxIcyYnEHQ5xjvJ6EkiXY1gq0MxbAgMBAAECgYBUTzqay2enTIaT0e6mTG7dTWM+uui5rftqMCWTGbkhaOP3NgWffM5ux1Ov566hG5A7a1+ltlRTnsfxxBNNhdVrMDyMFQVdvOgaUUeCCdn/Kvxr94Gzcy2AwerinxZP2LtOnKAD/YqJxUsV841cPwTO1sDh04UCINmYAvKQVO7qkQJBAOIzM1SSR6Gta+09FNzW0fs0a5+KhBQwhM5ma8V4e6c4oWzLXZfJIdnOZvkGy1hW4pwDgu+0L13Lz3i4x8MqTsMCQQCmxLgB6j3dOxPPmDbpFg8sZQISILiRX119ycthTmF1msI2wyZw70769uA55H+KNhw2UqFRRDJ71nJC9m7YgmKJAkEApNYG2+RVSt5jvdg7Mcth7Zt/qh14rnXE8dv1QUvRYESGbg+svoWVo3Ej3Ok0mcWHEYYFjsRRmBqDsEeHWxOjnQJBAIv+YVVCNNKNMFE5PwclvHERDc735tgqDQp2JqO1r3yRAG4GHjP5v/xO1+XhWetFByPW85KLxDFO0LZDtsNLmLkCQBpfFTH50511mu3WSgxNM6jg6qrPL/KtnNyHFYi2ELd4kGpQecG31TK1qz655rXk8LWILcMKnG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iqgM2jZBBxkJ0OvcQlTno9gdUu555Z0lWUEmlM6UyjvKy8hieY+CATd7R0Dh40aNB9V6q85URBQgu2gUyBQPGp8ql8MNvqTiVh0q8GNylm5BD0n2NbV1Vx9BeGHa0bnzd8kCSvrCOlKXU73fjez5gk0+suykT2IG6/nyAgRWVbuBcNVBDoku/UoyjTpbBbwhsIcKKnGNMYOBl2kfIhupjCkHykjRYoGjsgUrTiHbpsIIVJgwY/9VBkTU6He9/VBCFXCsRrS6V7ObJQ+UTrgXDS6Upmob+5LBB458MShGJ7m6V0b2Ilsxh8mJlWdYR7m6gQE+oPtVIKPYHVLueeWdJVlBJpTOlMrys6yLtM09yv4bjVn1TCXzAS9iCBLIAbaPdUfN1CEl/jKeZuipeMRc4lYdKvBjcpZuQQ9J9jW1dQfJuJHzGTK+35/Od4fY9aTg3pQbfWhnN4gKe3/ucHiHzdJCtYtvTyi1r3IMJTeEaGDzt6zhZ1DKdH60niPWNHc=";
		String ss = des_decrypt(data,"13868159894" + "5746dbf2-b880-4879-b706-1e4bf5f9e7cf");
		System.out.println(ss);
		String data1 = des_encrypt("{\"DATA\":{\"PARKING_RECORD_ID\":\"758bac83-b05b-4cd9-9678-01b8026b7f18\",\"LEAVE_TIME\":\"2018-09-19 14:02:15\"}}");
		System.out.println(data1);
		System.out.println(md5("3e56bfb8-1587-40c1-99a3-475404b189ab1537338576596" + data1));
	}
    
    public static String des_decrypt(String data){
        return des_decrypt(data,null);
    }

    public static String des_decrypt(String data, String key) {
        try{
            if (StringUtils.isBlank(data))return null;
            if(StringUtils.isBlank(key))key=CONSTANTS._DES_PWD;
            byte[] buf = Base64.decodeBase64(data);
            byte[] bt = decrypt(buf,key.getBytes(CONSTANTS.UTF8));
            return new String(bt);
        }catch(Exception e){
            return null;
        }
    }

    public static String aes_encrypt(String content, String key) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(key.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] byteRresult = cipher.doFinal(byteContent);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteRresult.length; i++) {
                String hex = Integer.toHexString(byteRresult[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String aes_decrypt(String content, String key) {
        if (content.length() < 1)
            return null;
        byte[] byteRresult = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            byteRresult[i] = (byte) (high * 16 + low);
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(key.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(byteRresult);
            return new String(result);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CONSTANTS.SECURITY_DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(CONSTANTS.SECURITY_DES);
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
        return cipher.doFinal(data);
    }

    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CONSTANTS.SECURITY_DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(CONSTANTS.SECURITY_DES);
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
        return cipher.doFinal(data);
    }
}
